package com.sakura.mybatis.builder;

import com.alibaba.druid.pool.DruidDataSource;
import com.sakura.mybatis.config.Configuration;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author wangxinyuchuan
 * @version XmlConfigBuilder.java v1.0 2025/4/15 15:39 wangxinyuchuan Exp $
 */
public class XmlConfigBuilder {

    private final Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parse(InputStream inputStream) throws ParserConfigurationException {
        try {
            Document document = new SAXReader().read(inputStream);
            Element rootElement = document.getRootElement();
            parseConfiguration(rootElement);
            return configuration;
        } catch (Exception e) {
            throw new ParserConfigurationException("解析配置文件出错");
        }
    }

    private void parseConfiguration(Element rootElement) throws DocumentException {
        if (rootElement == null) {
            return;
        }
        List<Element> propertyElements= rootElement.selectNodes("//property");

        Properties properties = new Properties();
        propertyElements.forEach(element ->  {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        });

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getProperty("driverClassName"));
        druidDataSource.setUrl(properties.getProperty("url"));
        druidDataSource.setUsername(properties.getProperty("username"));
        druidDataSource.setPassword(properties.getProperty("password"));
        druidDataSource.setConnectTimeout(Integer.parseInt(properties.getProperty("connectTimeout", "5000")));

        // 配置数据源
        configuration.setDataSource(druidDataSource);

        List<Element> mapperElements= rootElement.selectNodes("//mapper");

        XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
        for (Element element : mapperElements) {
            String mapperPath = element.attributeValue("resource");
            InputStream mapperStream = Resources.getResourceAsStream(mapperPath);
            xmlMapperBuilder.parse(mapperStream);
        }
    }
}
